package com.yoke.common;

import com.yoke.nginxlog.ReadLogJob;
import com.yoke.system.log.SystemLog;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Configuration;

/**
 * Created by jiangzeyin on 2017/8/8.
 */
@Configuration
public class ApplicationSpringUtil implements ApplicationListener<ApplicationReadyEvent> {
    private volatile static Scheduler scheduler = null;
    private static final StdSchedulerFactory STD_SCHEDULER_FACTORY = new StdSchedulerFactory();

    @Override
    public void onApplicationEvent(ApplicationReadyEvent applicationReadyEvent) {
        JobDetail job = JobBuilder.newJob(ReadLogJob.class)
                .withIdentity("adLog", "nginx")
                .build();
        CronTrigger trigger = TriggerBuilder.newTrigger()
                .withIdentity("adLog", "nginx")
                .withSchedule(CronScheduleBuilder.cronSchedule("0 0/5 * * * ?")).build();
        try {
            getScheduler().scheduleJob(job, trigger);
            // 开启调度
            getScheduler().start();
        } catch (SchedulerException e) {
            SystemLog.ERROR().error("启动任务失败", e);
        }
        SystemLog.LOG().info("启动日志分析成功");
    }


    /**
     * @return
     * @throws SchedulerException
     * @author jiangzeyin
     * @date 2016-9-1
     */
    private static Scheduler getScheduler() throws SchedulerException {
        // 通过schedulerFactory获取一个调度器
        if (scheduler == null) {
            synchronized (ApplicationSpringUtil.class) {
                scheduler = STD_SCHEDULER_FACTORY.getScheduler();
            }
        }
        return scheduler;
    }
}

